package com.kanshu.ksgb.fastread.doudou.module.bookcity.view;

import android.app.Activity;
import android.content.Context;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.app.constants.ARouterConfig;
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.AdStyleBean;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.AdUtils;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.BaseAdListener;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.presenter.AdPresenter;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.retrofit.ADConfigBean;
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.BookInfo;
import com.kanshu.ksgb.fastread.doudou.common.imageloader.GlideImageLoader;
import com.kanshu.ksgb.fastread.doudou.common.supertextview.SuperTextView;
import com.kanshu.ksgb.fastread.doudou.common.util.ARouterUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.DisplayUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.Utils;
import com.kanshu.ksgb.fastread.doudou.common.business.utils.BookUtils;
import com.kanshu.ksgb.fastread.doudou.module.bookcity.bean.ItemRefreshBean;
import com.kanshu.ksgb.fastread.doudou.module.bookcity.bean.SelectedBean;
import com.kanshu.ksgb.fastread.doudou.module.bookcity.presenter.BookCityPresenter;
import com.kanshu.ksgb.fastread.doudou.module.bookcity.utils.BookCityUtils;

import org.jetbrains.annotations.NotNull;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.subjects.PublishSubject;
import io.reactivex.subjects.Subject;

import static com.kanshu.ksgb.fastread.doudou.base.baseui.SwipeBackActivity.ACTION_DESTORY;

/**
 * Created by wcy on 18/5/15.
 */

public class AdSelectedTwoLayout extends LinearLayout implements IRefresh<SelectedBean> {

    @BindView(R.id.label)
    TextView mLabel;
    @BindView(R.id.cover)
    ImageView mCover;
    @BindView(R.id.book_title)
    TextView mBookTitle;
    @BindView(R.id.book_desc)
    TextView mBookDesc;
    @BindView(R.id.author)
    TextView mAuthor;
    @BindView(R.id.book_label)
    SuperTextView mBookLabel;
    @BindView(R.id.book_status)
    SuperTextView mBookStatus;
    @BindView(R.id.ad_container)
    FrameLayout mAdContainer;
    @BindView(R.id.sub_title)
    TextView mSubTitle;
    @BindView(R.id.people_num)
    TextView mPeopleNum;
    @BindView(R.id.bottom_container)
    LinearLayout mBottomContainer;
    ItemRefreshBean mItemRefreshBean;
    @BindView(R.id.change)
    TextView mChange;
    boolean mShowedAd;
    @BindView(R.id.change_tip)
    ImageView mChangeTip;
    public Subject<Integer> lifeCyclerSubject = PublishSubject.create();
    BookCityPresenter presenter;
    @BindView(R.id.root_container)
    RelativeLayout rootContainer;
    @BindView(R.id.ad_divider)
    LinearLayout mAdDivider;
    String mType;
    HashMap<String, Boolean> mShowNormalDatas = new HashMap<>();

    public AdSelectedTwoLayout(Context context) {
        super(context);
        init();
    }

    public AdSelectedTwoLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public AdSelectedTwoLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        presenter = new BookCityPresenter(lifeCyclerSubject);
        setOrientation(VERTICAL);
        View view = LayoutInflater.from(getContext()).inflate(R.layout.item_ad_selected_two_layout, this);
        ButterKnife.bind(view);

    }

    @Override
    public void refresh(SelectedBean selectedBean, Object object) {
        mItemRefreshBean = (ItemRefreshBean) object;
        if (selectedBean == null || mItemRefreshBean == null) {
            return;
        }
        mType = mItemRefreshBean.type;
        BookCityUtils.rotateCancel(mChangeTip);
        mLabel.setText(selectedBean.name);
        mLabel.setCompoundDrawablesWithIntrinsicBounds(mItemRefreshBean.selectionIcon, 0, 0, 0);
        if (!TextUtils.isEmpty(mItemRefreshBean.subTitle)) {
            mSubTitle.setText(mItemRefreshBean.subTitle);
            DisplayUtils.visible(mSubTitle);
        } else {
            DisplayUtils.gone(mSubTitle);
        }
        if (Constants.BookCityModuleType.TYPE_MALE_HUANFENLEI1.equals(mItemRefreshBean.type)
                || Constants.BookCityModuleType.TYPE_FEMALE_HUANFENLEI1.equals(mItemRefreshBean.type)) {
            mChange.setText("换分类");
        } else {
            mChange.setText("换一换");
        }
        if (Utils.isEmptyList(selectedBean.list)) {
            DisplayUtils.gone(mBottomContainer);
            return;
        }
        if (!Utils.isEmptyList(selectedBean.list)) {
            if (mShowNormalDatas.get(mType) != null
                    && mShowNormalDatas.get(mType)) {
                return;
            }
            for (int i = 0; i < mBottomContainer.getChildCount(); i++) {
                mBottomContainer.getChildAt(i).setVisibility(INVISIBLE);
            }
            if (selectedBean.list.size() > 4) {
                selectedBean.list = selectedBean.list.subList(0, 4);
            }
            BookInfo item = selectedBean.list.get(0);
            GlideImageLoader.load(item.cover_url, mCover);
            mBookTitle.setText(item.book_title);
            mBookDesc.setText(item.book_intro);
            mAuthor.setText(item.author_name);
            mBookLabel.setText(BookUtils.getBookLabel(item));
            mBookStatus.setText(BookUtils.getBookStatus(item));
            BookUtils.setStatusBg(mBookStatus, item);
            mPeopleNum.setText(BookUtils.formatNum(item.total_click_num) + "人在读");
            findViewById(R.id.root_container).setOnClickListener(v -> {
                ARouterUtils.toActivity(ARouterConfig.BOOK_DETAIL, "book_id", item.book_id);
                /**
                 * 检查显示的内容 埋点
                 */
                BookCityUtils.takeIf(mType,Constants.BookCityModuleType.TYPE_SELECTED_JINGXUANHAOSHU,()->{
                    AdPresenter.pvuvStatics(R.string.SCTUIJIAN2_POSITION1);

                });
            });
            if (Constants.BookCityModuleType.TYPE_MALE_DUSHISHENGHUO.equals(mItemRefreshBean.type)
                    || Constants.BookCityModuleType.TYPE_FEMALE_GONGWEIQINGCHOU.equals(mItemRefreshBean.type)
                    || Constants.BookCityModuleType.TYPE_MALE_HUANFENLEI1.equals(mItemRefreshBean.type)
                    || Constants.BookCityModuleType.TYPE_FEMALE_HUANFENLEI1.equals(mItemRefreshBean.type)) {
                DisplayUtils.visible(mPeopleNum);
                DisplayUtils.gone(mBookLabel, mBookStatus);
            } else {
                DisplayUtils.gone(mPeopleNum);
                DisplayUtils.visible(mBookLabel, mBookStatus);
            }
            for (int i = 1; i < selectedBean.list.size(); i++) {
                mBottomContainer.getChildAt(i - 1).setVisibility(VISIBLE);
                final int pos = i;
                mBottomContainer.getChildAt(i - 1).setOnClickListener(v -> {
                    ARouterUtils.toActivity(ARouterConfig.BOOK_DETAIL, "book_id", selectedBean.list.get(pos).book_id);

                    /**
                     * 检查显示的内容 埋点
                     */
                    BookCityUtils.takeIf(mType,Constants.BookCityModuleType.TYPE_SELECTED_JINGXUANHAOSHU,()->{
                        AdPresenter.pvuvStatics(pos-1,
                                R.string.SCTUIJIAN2_POSITION2,
                                R.string.SCTUIJIAN2_POSITION3,
                                R.string.SCTUIJIAN2_POSITION4);

                    });
                });
                FrameLayout frameLayout = (FrameLayout) mBottomContainer.getChildAt(i - 1);
                LinearLayout linearLayout = (LinearLayout) frameLayout.getChildAt(0);
                ImageView imageView = (ImageView) linearLayout.getChildAt(0);
                TextView tv1 = (TextView) linearLayout.getChildAt(1);
                SuperTextView tv2 = (SuperTextView) linearLayout.getChildAt(2);
                TextView tv3 = (TextView) linearLayout.getChildAt(3);
                GlideImageLoader.load(selectedBean.list.get(i).cover_url, imageView);
                tv1.setText(selectedBean.list.get(i).book_title);
                tv2.setText(BookUtils.getBookLabel(selectedBean.list.get(i)));
                tv3.setText(selectedBean.list.get(i).author_name);
                if (Constants.BookCityModuleType.TYPE_MALE_DUSHISHENGHUO.equals(mItemRefreshBean.type)
                        || Constants.BookCityModuleType.TYPE_FEMALE_GONGWEIQINGCHOU.equals(mItemRefreshBean.type)
                        || Constants.BookCityModuleType.TYPE_MALE_HUANFENLEI1.equals(mItemRefreshBean.type)
                        || Constants.BookCityModuleType.TYPE_FEMALE_HUANFENLEI1.equals(mItemRefreshBean.type)) {
                    DisplayUtils.visible(tv3, tv1);
                    DisplayUtils.gone(tv2);
                } else {
                    DisplayUtils.visible(tv1, tv2);
                    DisplayUtils.gone(tv3);
                }
            }
            mShowNormalDatas.put(mType, true);
        }
        // 添加广告
        DisplayUtils.gone(mAdContainer, mAdDivider);
        // 精选好书(男频)
        if (mItemRefreshBean.type.equals(Constants.BookCityModuleType.TYPE_SELECTED_JINGXUANHAOSHU)) {
            handleAd(ADConfigBean.POSITION_JINGXUANHAOSHU_BOTTOM_JX_1, AdStyleBean.IMAGE_TEXT_STYLE);
        }
        // 完结精品(男频)
        if (mItemRefreshBean.type.equals(Constants.BookCityModuleType.TYPE_MALE_WANJIEJINGDIAN)) {
            handleAd(ADConfigBean.POSITION_MALE_WANJIEJINGPING_BOTTOM_MP_3, AdStyleBean.IMAGE_TEXT_STYLE);
        }
        // 都市生活(男频)
        if (mItemRefreshBean.type.equals(Constants.BookCityModuleType.TYPE_MALE_HUANFENLEI1)) {
            handleAd(ADConfigBean.POSITION_MALE_DUSHISHENGHUO_BOTTOM_MP_5, AdStyleBean.IMAGE_TEXT_STYLE);
        }
        // 全本(女频)
        if (mItemRefreshBean.type.equals(Constants.BookCityModuleType.TYPE_FEMALE_QUANBEN)) {
            handleAd(ADConfigBean.POSITION_FEMALE_QUANBEN_BOTTOM_NP_3, AdStyleBean.IMAGE_TEXT_STYLE);
        }
        // 宫闱情仇(女频)
        if (mItemRefreshBean.type.equals(Constants.BookCityModuleType.TYPE_FEMALE_HUANFENLEI1)) {
            handleAd(ADConfigBean.POSITION_FEMALE_GONGWEIQINGCHOU_NP_5, AdStyleBean.IMAGE_TEXT_STYLE);
        }


    }

    private void handleAd(int positionId, int style) {
        DisplayUtils.visible(mAdContainer, mAdDivider);
        if (!mShowedAd) {
            AdUtils.fetchAdUtil((Activity) getContext(), mAdContainer, null, positionId, style, 0, new BaseAdListener() {
                @Override
                public void onAdLoadSucceeded(@org.jetbrains.annotations.Nullable View view) {
                    mShowedAd = true;
                    DisplayUtils.visible(mAdContainer, mAdDivider);
                }

                @Override
                public void onAdLoadFailed() {
                    DisplayUtils.gone(mAdContainer, mAdDivider);
                }

                @Override
                public void onAdClicked() {

                }

                @Override
                public void onADClosed() {
                    mShowedAd = false;

                }

                @Override
                public void onBackAd(@NotNull Object ad) {

                }
            });
        }
    }

    @Override
    public void onError(int code, String desc) {
        BookCityUtils.rotateCancel(mChangeTip);
    }

    @Override
    public void reset() {
        if (mShowNormalDatas != null) {
            mShowNormalDatas.clear();
        }
    }

    @OnClick(R.id.change_container)
    public void onViewClicked() {
        if (mItemRefreshBean == null) {
            return;
        }
        BookCityUtils.rotate(mChangeTip);
        mShowedAd = false;
        mShowNormalDatas.put(mType, false);
        if (Constants.BookCityModuleType.TYPE_MALE_HUANFENLEI1.equals(mItemRefreshBean.type)) {
            BookCityUtils.switchMaleCategory(mItemRefreshBean, this, null, presenter);
        } else if (Constants.BookCityModuleType.TYPE_FEMALE_HUANFENLEI1.equals(mItemRefreshBean.type)) {
            BookCityUtils.switchFemaleCategory(mItemRefreshBean, this, null, presenter);
        } else {
            BookCityUtils.refreshModuleInfos(mItemRefreshBean, this, presenter);
        }

        BookCityUtils.takeIf(mType,Constants.BookCityModuleType.TYPE_SELECTED_JINGXUANHAOSHU,()->{
            AdPresenter.pvuvStatics(R.string.SCTUIJIAN2_HUANYIHUAN);
        });

    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        lifeCyclerSubject.onNext(ACTION_DESTORY);
    }
}
